package com.asj.vivo.lock.service.binding;

import static com.asj.enums.AppIdentifierDictEnums.supervision_NotSave;
import static com.asj.enums.AppIdentifierDictEnums.supervision_cancel;
import static com.asj.enums.AppIdentifierDictEnums.supervision_initiate;
import static com.asj.enums.AppIdentifierDictEnums.supervision_isSave;
import static com.asj.enums.ControlProgressBarEnum.back_ground_binding_success;
import static com.asj.enums.ControlProgressBarEnum.bind_step;
import static com.asj.enums.ControlProgressBarEnum.binding_success;
import static com.asj.enums.ControlProgressBarEnum.get_local_device_info;
import static com.asj.enums.ControlProgressBarEnum.send_binding_request;
import static com.asj.enums.ControlProgressBarEnum.transfer_app_to_back_ground;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_ALL_OPERATION_INTERFACES;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_BATTER_PERCENTAGE;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_CODE;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_INFO;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_OP_KEY_BIND_DEVICE;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_PHONE_NUMBER;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_POSITION;
import static com.asj.enums.DeviceIdentifierDictEnums.DEVICE_WIFI_OR_FLOW;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_localAppData;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_result;
import static com.asj.enums.HttpRequestDictEnums.bindingDeviceUrl;
import static com.asj.enums.HttpRequestDictEnums.exchangeLocalAppInfoUrl;
import static com.asj.enums.ResultCodeEnums.request_error;
import static com.asj.enums.ResultCodeEnums.result_error;
import static com.asj.enums.ResultCodeEnums.result_success;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.asj.MainActivity;
import com.asj.MainActivityService;
import com.asj.annotation.AnnotationProcessor;
import com.asj.enums.ControlProgressBarEnum;
import com.asj.service.control.ControlProgressBarService;
import com.asj.service.oppoSdk.OPPOControlService;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.utils.HttpRequestUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 绑定服务之一：保存设备信息传输后台
 * */
public class BindingSaveDeviceService {

    /**
     * 存储设备信息
     * @param mainActivity 主活动程序类
     * */
    public static void saveDevice(MainActivity mainActivity){
        //oppoSDK服务接口
        OPPOSDKService opposdkService = new OPPOSDKService(mainActivity);
        //获取设备码
        String deviceCode = opposdkService.getIMEI();
        //标识 —— 获取设备信息的箱子
        JsonObject deviceInfo = null;
        try {
            ControlProgressBarEnum.setValueAndMessage(get_local_device_info);
            //获取设备信息
            deviceInfo = getEntries(opposdkService, mainActivity, deviceCode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //---添加进度列表
        ControlProgressBarEnum.setValueAndMessage(send_binding_request);
        //发送添加设备的请求
        String resultMsg = HttpRequestUtils.retryHttpRequest(bindingDeviceUrl.getValue(),deviceInfo.toString(),null,3,mainActivity);
        if(resultMsg.equals(result_error.getMessage())){
            JsonObject bindingDeviceResult = JsonParser.parseString(resultMsg).getAsJsonObject();
            //解除锁机
            new OPPOControlService(mainActivity).unlockMachine(false);
            if(bindingDeviceResult != null){
                ControlProgressBarService.setProgressBarAndListValue(bind_step.getValue(),"绑定设备失败！--"+ bindingDeviceResult.get("message").getAsString());
            }
        }else{
            //---添加进度列表
            ControlProgressBarEnum.setValueAndMessage(back_ground_binding_success); //解除锁机
            afterSaveDevice(mainActivity,deviceCode);
        }
    }
    /**
     * 添加设备成功后的处理事项
     * @param mainActivity 主活动程序类
     * @param deviceCode 设备编码（IMEI）
     * */
    public static void afterSaveDevice(MainActivity mainActivity,
                                       String deviceCode){
        OPPOControlService oppoControlService = new OPPOControlService(mainActivity);
        try{
            /* 1.设置监管 */
            oppoControlService.initiateOrCancelSupervision(supervision_isSave.getValue(),supervision_initiate.getValue());

            /* 2.异步传输+校验app */
            ExecutorServiceInputApp(mainActivity,deviceCode);
            ControlProgressBarEnum.setValueAndMessage(transfer_app_to_back_ground);

            /* 3.启动后台常驻服务 */
            MainActivityService.startService(mainActivity);

            /* 4.绑定完成 */
            ControlProgressBarEnum.setValueAndMessage(binding_success);
            //发布通知告诉设备正常
//            CommonsUtils.showNotification(mainActivity,"设备绑定成功","设备已处于监管中");

            new OPPOControlService(mainActivity).unlockMachine(false);
            new Handler(Looper.getMainLooper()).postDelayed(mainActivity::finishAffinity, 3000); // 延时2000毫秒（2秒）后执行
        }catch (Exception e){
            //解锁设备
            oppoControlService.unlockMachine(false);
            //未绑定设备，解除监管
            oppoControlService.initiateOrCancelSupervision(supervision_NotSave.getValue(),supervision_cancel.getValue());
            Log.e("设置监管异常！", Objects.requireNonNull(e.getMessage()));
        }
    }

    /**
     * 异步传输app方法
     * @param mainActivity 主活动程序类
     * @param deviceCode 设备编码（IMEI）
     * */
    public static void  ExecutorServiceInputApp(MainActivity mainActivity,
                                                String deviceCode){
        //异步传输app
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        //请求获取所有本地的app信息
        String result = HttpRequestUtils.retryHttpRequest(exchangeLocalAppInfoUrl.getValue(), null, result_success.getCode(), 3, mainActivity);
        if(!request_error.getMessage().equals(result)){
            //解析result
            JsonObject localAppData = JsonParser.parseString(result).getAsJsonObject();
            JsonObject localAppDataResult = JsonParser.parseString(localAppData.get(json_key_result.getValue()).getAsString()).getAsJsonObject();
            String localAppDataStr = localAppDataResult.get(json_key_localAppData.getValue()).getAsString();
            //指定转换类型
            List<String> localAppList = Arrays.asList(localAppDataStr.split(","));
            executorService.execute(() -> {
                //进行异步开始校对app之间的数据是否正确
                AppInfoHandlerService.getInstance(mainActivity).checkAppList(localAppList
                        ,mainActivity
                        ,deviceCode);
            });
        }
    }

    /**
     * 获取设备信息的封装方法
     * @param opposdkService 调用oppo操作接口的主服务接口
     * @param mainActivity 主活动程序类
     * @param deviceCode 设备编码（IMEI）
     * */
    private static JsonObject getEntries(OPPOSDKService opposdkService,
                                         MainActivity mainActivity,
                                         String deviceCode) throws Exception {
        //通过SDK接口 获取各项设备信息
        String getDeviceInfoBySDK = opposdkService.getDeviceInfo();
        String phoneNumber = opposdkService.PhoneNumber();
        String devicePosition = opposdkService.getDevicePosition();
        //通过android 获取各项设备信息
        BindingGetDeviceInfoService getDeviceInfoService = BindingGetDeviceInfoService.getInstance(mainActivity);
        String batteryPercentage = getDeviceInfoService.getBatteryPercentage();
        int wifiOrFlow = getDeviceInfoService.getWifiOrFlow();

        //封装设备信息
        JsonObject deviceInfo = new JsonObject();
        //说明这条指令是要绑定设备操作
        deviceInfo.addProperty(DEVICE_OP_KEY_BIND_DEVICE.getValue(),"0");
        //传递设备标识 串码
        deviceInfo.addProperty(DEVICE_CODE.getValue(), deviceCode);
        //设备的基本信息
        deviceInfo.addProperty(DEVICE_INFO.getValue(),getDeviceInfoBySDK);
        //电量
        deviceInfo.addProperty(DEVICE_BATTER_PERCENTAGE.getValue(),batteryPercentage);
        //电话号码
        deviceInfo.addProperty(DEVICE_PHONE_NUMBER.getValue(),phoneNumber);
        //地理位置——经纬度
        deviceInfo.addProperty(DEVICE_POSITION.getValue(),devicePosition);
        //传输网络类型
        deviceInfo.addProperty(DEVICE_WIFI_OR_FLOW.getValue(),wifiOrFlow);

        //传输所有的可操作接口信息
        deviceInfo.addProperty(DEVICE_ALL_OPERATION_INTERFACES.getValue(), AnnotationProcessor.getAnnotatedMethodsInfo(OPPOSDKService.class).toString());
        return deviceInfo;
    }

}
